//
//  BaseWebViewController.m
//  Kaagad Peso
//
//  Created by ZhengChengFeng on 2024/10/15.
//

#import "BaseWebViewController.h"
#import <WebKit/WebKit.h>
#import <StoreKit/StoreKit.h>
#import <StoreKit/SKStoreReviewController.h>

@interface BaseWebViewController ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler,CLLocationManagerDelegate>

@property (nonatomic) WKWebView *webView;

@property (nonatomic) NSString *startTimeStr,*endTimeStr;
@property (nonatomic) CLLocationManager *locationManager;
@property (nonatomic) NSTimer *timer;
@property (nonatomic) NSInteger timeInt;
@property (nonatomic) BOOL isLocationSuccess;
@property (nonatomic) NSString *orderIdStr,*orderNoStr;

@end

@implementation BaseWebViewController

- (void)back{
    if (self.webView.canGoBack == YES) {
        [self.webView goBack];
        return;
    }
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [BoxLoadingHelper hideBoxLoading];
    [BoxLoadingHelper hideBoxLoadingFromView:self.webView];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
}

- (WKWebView *)webView {
    if (!_webView) {
        
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        config.userContentController = [WKUserContentController new];
        
        NSArray *methodArr = @[@"provender",@"family",@"justified",@"come",@"parties",@"healthfuller"];
        [methodArr enumerateObjectsUsingBlock:^(NSString *methodStr, NSUInteger idx, BOOL * _Nonnull stop) {
            [config.userContentController addScriptMessageHandler:self name:methodStr];
        }];
        
        WKPreferences *preferences = [WKPreferences new];
        preferences.javaScriptCanOpenWindowsAutomatically = YES;
        config.preferences = preferences;
 
        _webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:config];
        _webView.navigationDelegate = self;
        _webView.UIDelegate = self;
        _webView.scrollView.showsVerticalScrollIndicator = NO;
        _webView.scrollView.showsHorizontalScrollIndicator = NO;
        _webView.allowsBackForwardNavigationGestures = YES;

    }
    return _webView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.webView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - kNavigationBarHeight);
    
    [self.view addSubview:self.webView];

    [BoxLoadingHelper showBoxLoadingWithMessage:@"" onView:self.webView withOriginY:-kNavigationBarHeight];

    NSURL *url = [NSURL URLWithString:esString(self.urlStr)];
    
    [self.webView loadRequest:[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15.0f]];
}

#pragma mark - - WKNavigationDelegate
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation{
}

- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation{
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{
    [BoxLoadingHelper hideBoxLoading];
    [BoxLoadingHelper hideBoxLoadingFromView:self.webView];
    [webView evaluateJavaScript:@"document.title" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        if (error == nil) {
            if (result != nil) {
                self.title = [NSString stringWithFormat:@"%@",esString(result)];
            }
        }
    }];

}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(nonnull NSError *)error{
    [BoxLoadingHelper hideBoxLoading];
    [BoxLoadingHelper hideBoxLoadingFromView:self.webView];
}

- (void) webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction*) navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    decisionHandler(WKNavigationActionPolicyAllow);
}

#pragma mark - WKScriptMessageHandler
- (void)userContentController:(nonnull WKUserContentController *)userContentController didReceiveScriptMessage:(nonnull WKScriptMessage *)message {
    
    id body = message.body;
   
    if ([message.name isEqualToString:@"provender"]){
        if (isArray(body)) {
            NSArray *ary = body;
        
            self.orderIdStr =  esString(ary.firstObject);
            self.orderNoStr =  esString(ary.lastObject);
            
            self.startTimeStr = [NSString getNowTimeTimestamp:@"yyyyMMdd HH:mm:ss"];
            self.endTimeStr = esString([NSString getNowTimeTimestamp:@"yyyyMMdd HH:mm:ss"]);
            [self uploadMaiDianSDEndData];
            
        }
        
    }
    else if ([message.name isEqualToString:@"family"]){
        if (isArray(body)) {
            NSArray *bodyArr = body;
            [[DKCore sharedDKCore] jumpToControllerWithUrlString:bodyArr.firstObject];
        }
        
    }
    else if ([message.name isEqualToString:@"parties"]){
        if (isArray(body)) {
            NSArray *bodyArr = body;
            NSString *str = bodyArr.firstObject;
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"mailto:%@",str]] options:@{} completionHandler:^(BOOL success) {
            }];
        }
    }
    else if ([message.name isEqualToString:@"healthfuller"]){
        [SKStoreReviewController requestReview];
    }
    else if ([message.name isEqualToString:@"justified"]){
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
    else if ([message.name isEqualToString:@"come"]){
        [self.navigationController popToRootViewControllerAnimated:NO];
        [self.tabBarController setSelectedIndex:0];
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationTabBarNum object:nil userInfo:@{@"index":@"1"}];
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
 #pragma mark - Navigation

 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

#pragma mark ----- uploadMaiDianSDEndData -------
- (void)uploadMaiDianSDEndData{
    self.timeInt = 0;
    self.isLocationSuccess = NO;
    [self initLocation];
}

- (void)initLocation{
    self.timer = [NSTimer timerWithTimeInterval:1.f target:self selector:@selector(addTimer) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    
    self.locationManager = [[CLLocationManager alloc]init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = 100;
    [self.locationManager requestWhenInUseAuthorization];
    [self.locationManager requestLocation];
}

- (void)addTimer{
    self.timeInt ++;
    if (self.isLocationSuccess) {
        [self.timer invalidate];
        self.timer = nil;
        self.timeInt = 0;
    }
    else{
        if (self.timeInt > 8) {
            [self.timer invalidate];
            self.timer = nil;
            self.timeInt = 0;
            NSString *longitudeStr = [[NSUserDefaults standardUserDefaults] objectForKey:kStoreLongitude];
            NSString *latitudeStr = [[NSUserDefaults standardUserDefaults] objectForKey:kStoreLatitude];
            
            [self goServerWithLongitudeStr:PMStringIsEmpty(longitudeStr) ? @"" : longitudeStr withLatitudeStr:PMStringIsEmpty(latitudeStr) ? @"" : latitudeStr];
            
        }
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    
    CLLocation *newlocation = locations[0];
    NSString *longitudeStr = [NSString stringWithFormat:@"%lf",newlocation.coordinate.longitude];
    NSString *latitudeStr =  [NSString stringWithFormat:@"%lf",newlocation.coordinate.latitude];
    [self.locationManager stopUpdatingLocation];
    
    
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kStoreLongitude];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kStoreLatitude];
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%lf",newlocation.coordinate.longitude] forKey:kStoreLongitude];
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%lf",newlocation.coordinate.latitude] forKey:kStoreLatitude];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    self.isLocationSuccess = YES;
    
    if (self.timeInt <= 8) {
        [self goServerWithLongitudeStr:esString(longitudeStr) withLatitudeStr:esString(latitudeStr)];
    }

}

- (void)goServerWithLongitudeStr:(NSString *)longitudeStr withLatitudeStr:(NSString *)latitudeStr{
    [DataCategoryUpload uploadMaiDianData:@"9" withOrderIdStr:esString(self.orderIdStr) withOrderNoStr:esString(self.orderNoStr) withLongitude:esString(longitudeStr) withLatitude:esString(latitudeStr) withStartTime:self.startTimeStr withEndTime:self.endTimeStr];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    
}

@end
